import os
import uuid
from fastapi import APIRouter, UploadFile, File, HTTPException, status, Depends
from fastapi.responses import FileResponse
from sqlalchemy.orm import Session
from typing import List, Optional
from app.core.deps import get_current_active_user
from app.db.database import get_db
from app.models.product import ProductImage
from app.schemas.product import ProductImageCreate, ProductImage as ProductImageSchema

router = APIRouter()

# 图片存储目录
UPLOAD_DIR = "uploads"
if not os.path.exists(UPLOAD_DIR):
    os.makedirs(UPLOAD_DIR)

@router.post("/images/", response_model=List[ProductImageSchema])
async def upload_images(
    files: List[UploadFile] = File(...),
    product_id: Optional[int] = None,
    db: Session = Depends(get_db),
    current_user = Depends(get_current_active_user)
):
    """上传多张图片"""
    uploaded_images = []
    
    for file in files:
        # 检查文件类型
        if not file.content_type.startswith('image/'):
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"File {file.filename} is not an image"
            )
        
        # 生成唯一文件名
        file_extension = os.path.splitext(file.filename)[1]
        unique_filename = f"{uuid.uuid4()}{file_extension}"
        file_path = os.path.join(UPLOAD_DIR, unique_filename)
        
        # 保存文件
        try:
            with open(file_path, "wb") as buffer:
                content = await file.read()
                buffer.write(content)
        except Exception as e:
            raise HTTPException(
                status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
                detail=f"Failed to save file: {str(e)}"
            )
        
        # 创建数据库记录
        db_image = ProductImage(
            filename=unique_filename,
            original_filename=file.filename,
            file_path=file_path,
            file_size=len(content),
            content_type=file.content_type,
            product_id=product_id
        )
        db.add(db_image)
        uploaded_images.append(db_image)
    
    db.commit()
    
    # 刷新所有上传的图片记录
    for image in uploaded_images:
        db.refresh(image)
    
    return uploaded_images

@router.get("/images/{image_id}")
async def get_image(image_id: int, db: Session = Depends(get_db)):
    """获取图片文件 - 无需认证"""
    image = db.query(ProductImage).filter(ProductImage.id == image_id).first()
    if not image:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Image not found"
        )
    
    if not os.path.exists(image.file_path):
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Image file not found"
        )
    
    return FileResponse(
        path=image.file_path,
        media_type=image.content_type,
        filename=image.original_filename
    )

@router.get("/images/", response_model=List[ProductImageSchema])
async def get_images(
    product_id: int = None,
    skip: int = 0,
    limit: int = 100,
    db: Session = Depends(get_db)
):
    """获取图片列表 - 无需认证"""
    query = db.query(ProductImage)
    if product_id:
        query = query.filter(ProductImage.product_id == product_id)
    
    images = query.offset(skip).limit(limit).all()
    return images

@router.delete("/images/{image_id}")
async def delete_image(
    image_id: int,
    db: Session = Depends(get_db),
    current_user = Depends(get_current_active_user)
):
    """删除图片"""
    image = db.query(ProductImage).filter(ProductImage.id == image_id).first()
    if not image:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Image not found"
        )
    
    # 删除文件
    if os.path.exists(image.file_path):
        try:
            os.remove(image.file_path)
        except Exception as e:
            # 记录错误但不阻止删除数据库记录
            print(f"Failed to delete file {image.file_path}: {str(e)}")
    
    # 删除数据库记录
    db.delete(image)
    db.commit()
    
    return {"message": "Image deleted successfully"}

@router.put("/images/{image_id}/product")
async def associate_image_with_product(
    image_id: int,
    product_id: int,
    db: Session = Depends(get_db),
    current_user = Depends(get_current_active_user)
):
    """关联图片到商品"""
    image = db.query(ProductImage).filter(ProductImage.id == image_id).first()
    if not image:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Image not found"
        )
    
    # 检查商品是否存在
    from app.models.product import Product
    product = db.query(Product).filter(Product.id == product_id).first()
    if not product:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Product not found"
        )
    
    image.product_id = product_id
    db.commit()
    db.refresh(image)
    
    return image 